package main

import (
	"go-monitor/agent/service"
	"go-monitor/common/utility"
	"log"
	"os"
	"os/exec"
	"strings"
	"time"

	"github.com/astaxie/beego/logs"
	uservice "github.com/kardianos/service"
)

var root string

var Logger *logs.BeeLogger

func InitLog() {
	logdir := root + "/var/logd/"
	if !utility.PathExists(logdir) {
		err := os.MkdirAll(logdir, os.ModeDir)
		if err != nil {
			log.Println("log dir create fail")
			os.Exit(1)
		}
	}
	Logger = logs.NewLogger(100000)
	Logger.SetLogger(logs.AdapterFile, `{"filename":"var/logd/run.log"}`)
	Logger.SetLogger(logs.AdapterConsole)
	Logger.EnableFuncCallDepth(true)
}

func main() {
	var err error
	root, err = os.Getwd()
	if err != nil {
		log.Println("getwd fail:", err)
		os.Exit(1)
	}
	InitLog()

	cfg := &uservice.Config{
		Name:        "go-agentd",
		DisplayName: "go-monitor agentd service",
		Description: "go-monitor agent guard process service",
	}
	prg := &service.Program{Run: rund}
	ser, err := uservice.New(prg, cfg)
	if err != nil {
		Logger.Error("生成服务异常", err)
	}
	if len(os.Args) > 1 {
		err = uservice.Control(ser, os.Args[1])
		if err != nil {
			Logger.Error("生成服务异常1", err)
		}
	} else {
		ser.Run()
	}
}

func rund() {
	for {
		root = strings.Replace(root, "/agentd", "", -1)
		cmd := exec.Command("/bin/sh", "-c", `[[ -z $(ps -ef | grep -w `+root+`"/agent" | grep -v grep) ]] && echo "0" || echo "1"`)
		output, _ := cmd.Output()
		if strings.TrimSpace(string(output)) == "0" {
			func() {
				if utility.PathExists(root + "/agent_new") {
					cmd := exec.Command("/bin/sh", "-c", "chmod 777 "+root+"/agent_new")
					cmd.Run()
					time.Sleep(100 * time.Millisecond)
					cmd = exec.Command("/bin/sh", "-c", "mv -f "+root+"/agent_new "+root+"/agent")
					err := cmd.Run()
					if err != nil {
						Logger.Error("更新替换agent文件异常", err)
					}
				}
				cmd := exec.Command("/bin/sh", "-c", "nohup "+root+"/agent &")
				err := cmd.Run()
				if err != nil {
					Logger.Error(err.Error())
				}
			}()
		}
		time.Sleep(1000 * time.Millisecond)
	}
}
